<?php

/**
 * 投票模块-投票操作
 * @desc
 */
class Api_Vote_Poll extends PhalApi_Api {

    public function getRules() {
        return [

            'add'        => [
                'userid'     => ['name' => 'userid', 'type' => 'string','min' => 1, 'max' => 100000, 'require' => true, 'desc' => '候选人id'],
                'itemid'   => ['name' => 'itemid', 'type' => 'string', 'require' => true, 'desc' => '所属项目id'],
                'openid' => ['name' => 'openid', 'type' => 'string', 'require' => true, 'desc' => '微信openid']
            ],
            'lists'      => [
                'itemid' => ['name' => "itemid", 'type' => 'string', 'require' => true, 'desc' => '所属项目id']
            ],

        ];
    }

    /**
     * 投票
     * @desc
     * @return int ret HTTP状态码,200成功,其他失败
     * @return boolean data.isadded 是否投票成功
     * @return string msg 提示信息
     */
    public function add() {
        $db = new Domain_Vote();
        $itemInfo = $db->itemGet($this->itemid);
        if (!$itemInfo) {
            throw new PhalApi_Exception("未找到该项目", 10002);
        };
        $curr_date = time();
        if (strtotime($itemInfo['startTime']) > $curr_date) {
            throw new PhalApi_Exception(strtotime($itemInfo['startTime']) . "未到投票时间" . $curr_date, 10003);
        }
        if (strtotime($itemInfo['endTime']) < $curr_date) {
            throw new PhalApi_Exception("投票已结束", 10004);
        }

//        DATE("Y-m-d")
        $todayTotal = $db->historyUserByDay($this->openid, DATE("Y-m-d"));
        if ($todayTotal >= $itemInfo['userLimit']) {
            throw new PhalApi_Exception("今日投票次数已用完", 10005);
        }
        $todayTotal = $db->historyUserByDay($this->openid, DATE("Y-m-d"), $this->userid);
        if ($todayTotal >= $itemInfo['nomineeLimit']) {
            throw new PhalApi_Exception("同一同一天候选人最多投" . $itemInfo['nomineeLimit'] . "票", 10006);
        }
        if (!$db->hasNameInItem($this->userid, $this->itemid)) {
            throw new PhalApi_Exception("候选人不存在", 10007);
        };


        if (!$db->historyAddUser($this->openid, $this->userid, $this->itemid)) {
            throw new PhalApi_Exception("投票失败", 10008);
        };
        if (!$db->NamePlus($this->userid, $this->itemid)) {
            throw new PhalApi_Exception("投票失败", 10009);
        }
        return ['isadded' => true];

    }



    /**
     * 获取项目投票数列表
     * @desc
     * @return int ret HTTP状态码,200成功,其他失败
     * @return array data 数据列表
     * @return string name 姓名
     * @return string poll 投票数
     * @return string headimgurl 头像地址
     * @return string no 投票编号 唯一
     * @return string msg 提示信息
     */
    public function lists() {
        $db = new Domain_Vote();
        return $db->getlist($this->itemid);
    }


}
